package com.dingtalk;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkim_1_0.Client;
import com.aliyun.dingtalkim_1_0.models.SendInteractiveCardHeaders;
import com.aliyun.dingtalkim_1_0.models.SendInteractiveCardRequest;
import com.aliyun.dingtalkim_1_0.models.SendInteractiveCardResponse;
import com.aliyun.dingtalkim_1_0.models.SendInteractiveCardResponseBody;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTOHeaders;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTORequest;
import com.aliyun.dingtalkrobot_1_0.models.BatchSendOTOResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.constant.AppConstant;
import com.dingtalk.util.AccessTokenUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

import static com.dingtalk.Sample.createClient;


/**
 * 实现了机器人的简单问答功能
 */
@RestController
public class SingleRobotsController {


    @RequestMapping(value = "/singleRobots")
    public String helloRobots(@RequestBody(required = false) JSONObject json) throws Exception {
        String text = JSON.toJSONString(json.get("text"));
        String userId = json.get("senderStaffId").toString();
        String outTrackId = String.valueOf(System.currentTimeMillis() / 1000);
        Map<String, String> cardDataCardParamMap = new HashMap<>();
        String content = JSON.parseObject(text).getString("content");

        if (content.contains("报销")) {
            cardDataCardParamMap.put("q1", "餐补无发票如何报销");
            cardDataCardParamMap.put("q2", "和其他子集团同事出差，能否一起报销");
            cardDataCardParamMap.put("q3", "先付款后补发票，怎么走流程");
            cardDataCardParamMap.put("q4", "财务冲账流程怎么走");
            cardDataCardParamMap.put("q5", "挂账付款怎么修改申请人");
            cardDataCardParamMap.put("q6", "财务共享费用报销申请如何关联OA");
            cardDataCardParamMap.put("q7", "对公挂账如何关联OA");
            cardDataCardParamMap.put("q8", "服务器内部显示异常，无法上传");
            cardDataCardParamMap.put("q9", "报销申请提交后显示，不允许重复驳回");
            cardDataCardParamMap.put("q11", "如何添加银行账号");
            cardDataCardParamMap.put("q12", "提交报销申请,未配置成本中心");
            cardDataCardParamMap.put("q13", "对公报账出现单据预算冻结失败");
            cardDataCardParamMap.put("q14", "报销搜不到员工银行账号，怎么办");
            cardDataCardParamMap.put("q15", "出差流程怎么保存到桌面");
            cardDataCardParamMap.put("q10", "私车公用油卡费用到票核销，不属于公车，怎么选择公车车牌");
            String cardTemplateId = AppConstant.BX_CARD_TEMPLATE_ID;
            // 发送互动卡片消息
            return sendInteractiveCardMessage(outTrackId, cardDataCardParamMap, userId, cardTemplateId);
        } else if (content.contains("发票")) {
            cardDataCardParamMap.put("q1", "申请费用报销，如何录入发票");
            cardDataCardParamMap.put("q2", "发票查验失败怎么办");
            cardDataCardParamMap.put("q3", "电子专票怎么上传查验");
            cardDataCardParamMap.put("q4", "发票采集出现外部识别接口失败");
            cardDataCardParamMap.put("q5", "发票查验，未知异常");
            cardDataCardParamMap.put("q6", "开票/收票单位不存在，请先维护");
            cardDataCardParamMap.put("q7", "政府机构银行账号没有纳税人识别号");
            cardDataCardParamMap.put("q8", "登陆财务共享报销时关联不到发票怎么办");
            cardDataCardParamMap.put("q9", "有发票未关联业务小类");
            String cardTemplateId = AppConstant.FP_CARD_TEMPLATE_ID;
            // 发送互动卡片消息
            return sendInteractiveCardMessage(outTrackId, cardDataCardParamMap, userId, cardTemplateId);
        } else if (content.contains("账号")) {
            cardDataCardParamMap.put("q1", "首次登陆账号、密码是多少");
            cardDataCardParamMap.put("q2", "显示账号不存在");
            cardDataCardParamMap.put("q3", "账号冻结、忘记密码怎么办");
            String cardTemplateId = AppConstant.ZH_CARD_TEMPLATE_ID;
            // 发送互动卡片消息
            return sendInteractiveCardMessage(outTrackId, cardDataCardParamMap, userId, cardTemplateId);
        } else {
            sendMessages(userId);
            return null;
        }
    }

    /**
     * 发送互动卡片消息
     * @param outTrackId
     * @param cardDataCardParamMap
     * @param userId
     * @param cardTemplateId
     * @return
     */
    public String sendInteractiveCardMessage(String outTrackId, Map<String, String> cardDataCardParamMap, String userId, String cardTemplateId) {
        try {
            Client client = AccessTokenUtil.createClient();
            Map<String, String> cardDataCardMediaIdParamMap = new HashMap<>();
            SendInteractiveCardHeaders sendInteractiveCardHeaders = new SendInteractiveCardHeaders();
            sendInteractiveCardHeaders.xAcsDingtalkAccessToken = AccessTokenUtil.getAccessToken();
            SendInteractiveCardRequest.SendInteractiveCardRequestCardData cardData = new SendInteractiveCardRequest.SendInteractiveCardRequestCardData()
                    .setCardMediaIdParamMap(cardDataCardMediaIdParamMap)
                    .setCardParamMap(cardDataCardParamMap);
            SendInteractiveCardRequest sendInteractiveCardRequest = new SendInteractiveCardRequest()
                    .setCardTemplateId(cardTemplateId)
                    .setReceiverUserIdList(java.util.Arrays.asList(userId))
                    .setCallbackRouteKey("dingding")
                    .setOutTrackId(outTrackId)
                    .setConversationType(0)
                    .setCardData(cardData);
            SendInteractiveCardResponse rsp = client.sendInteractiveCardWithOptions(sendInteractiveCardRequest, sendInteractiveCardHeaders, new RuntimeOptions());
            SendInteractiveCardResponseBody body = rsp.getBody();
            return "success";
        } catch (Exception e) {
            System.out.println("互动卡片消息发送失败" + e);
            return "fail";
        }

    }

    /**
     * 发送基本消息
     *
     * @param userId
     * @throws Exception
     */
    public void sendMessages(String userId) throws Exception {
        com.aliyun.dingtalkrobot_1_0.Client client = createClient();
        BatchSendOTOHeaders batchSendOTOHeaders = new BatchSendOTOHeaders();
        batchSendOTOHeaders.xAcsDingtalkAccessToken = AccessTokenUtil.getAccessToken();
        BatchSendOTORequest batchSendOTORequest = new BatchSendOTORequest()
                .setRobotCode(AppConstant.APP_KEY)
                .setUserIds(java.util.Arrays.asList(userId))
                .setMsgKey("sampleActionCard3")
                .setMsgParam("{\n" +
                        "        \"title\": \"问题类型\",\n" +
                        "        \"text\": \"请问您是要咨询什么问题类型\",\n" +
                        "        \"actionTitle1\": \"报销类\",\n" +
                        "        \"actionURL1\": \"dtmd://dingtalkclient/sendMessage?content=%E6%8A%A5%E9%94%80%E7%B1%BB\",\n" +
                        "        \"actionTitle2\": \"发票类\",\n" +
                        "        \"actionURL2\": \"dtmd://dingtalkclient/sendMessage?content=%E5%8F%91%E7%A5%A8%E7%B1%BB\",\n" +
                        "        \"actionTitle3\": \"账号类\",\n" +
                        "        \"actionURL3\": \"dtmd://dingtalkclient/sendMessage?content=%E8%B4%A6%E5%8F%B7%E7%B1%BB\"\n" +
                        "    }");
        try {
            BatchSendOTOResponse batchSendOTOResponse = client.batchSendOTOWithOptions(batchSendOTORequest, batchSendOTOHeaders, new RuntimeOptions());
            System.out.println(JSON.toJSONString(batchSendOTOResponse.getBody()));
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.code);
                System.out.println(err.message);
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                System.out.println(err.code);
                System.out.println(err.message);
            }
        }
    }

}
